<template>
  <div class="login">
    <div class="title-container">
      <h3 class="title">OJ系统 培训师登录</h3>
    </div>
    <div class="login-form-container">
      <img src="../assets/极课堂logo.png" style="margin: 40px 192px 10px 192px; width: 136px; height: 33px">


      <el-form ref="loginForm2" :rules="loginFormRules" :model="loginForm" class="login-form">
        <el-form-item prop="phone">
          <el-input v-model="loginForm.phone" placeholder="请输入手机号">
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="loginForm.password" placeholder="请输入密码">
          </el-input>
        </el-form-item>
        <el-button class="login-button1" @click="loginSubmit()">登录</el-button>
      </el-form>
      <el-dialog v-model="firstLogin" title="首次登录请先修改密码" width="500" :showClose="false" :closeOnClickModal="false">
        <el-form :model="register" :rules="userInfoFormRules">
          <el-form-item :label-width="formLabelWidth" prop="username">
            <el-input v-model="register.username" autocomplete="off" placeholder="请输入用户名"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" prop="mobile">
            <el-input v-model="register.phone" autocomplete="off" placeholder="请输入手机号"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" prop="password">
            <el-input v-model="register.password" autocomplete="off" type="password" placeholder="请输入新密码"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth">
            <div class="codeDiv">
              <el-input class="registerCode" v-model="register.code" autocomplete="off" placeholder="请输入验证码"/>
              <el-button class="getRegisterCode" @click="getCode">获取验证码</el-button>
            </div>
          </el-form-item>
          <div style="display: flex">
          <el-button type="primary" @click="cancel">
            取消
          </el-button>
          <el-button type="primary" @click="registerPhone">
            激活
          </el-button>
          </div>
        </el-form>

        <!--        滑块验证-->
        <div >
          <Vcode :show="isShow" @success="success" @close="close" @fail='fail' ></Vcode>
        </div>
      </el-dialog>

    </div>
  </div>

</template>
<script setup>
import {reactive, ref,onMounted} from 'vue'
import {useStore} from 'vuex'
import {useRouter} from 'vue-router'
import {JSEncrypt} from "jsencrypt";
import {ElMessage} from "element-plus";
import API from '@/api/base/base'
import Vcode from "vue3-puzzle-vcode";

let isShow=ref(false)
import store from "@/store";

onMounted(() => {
  // console.log('value:', props.value)
  store.commit('user/out')
})
const entry = new JSEncrypt()
const success=()=>{
  isShow.value=false
  API.getPublic().then((res) => {
    if (res.data.code === '0') {
      // 使用jsencrypt加密
      entry.setPublicKey(res.data.content.publicKeyStr)
      registerSubmitForm.username = entry.encrypt(register.username)
      registerSubmitForm.phone = entry.encrypt(register.phone)
      registerSubmitForm.role = entry.encrypt('3')
      registerSubmitForm.random = res.data.content.random
      registerSubmitForm.password=entry.encrypt(register.password)
      API.getPhoneCode(registerSubmitForm).then((res) => {
        if (res.data.code === '0') {
          ElMessage.success('验证通过,已发送验证码')
        }
      }).catch(response => {
        ElMessage.error(response.response.data.message)
      })
    }
  }).catch(error => {
    console.log(error)
  })
}
// 激活
const registerPhone = () => {
  registerSubmitForm.code=entry.encrypt(register.code)
  API.adminactivity(registerSubmitForm).then((res) => {
    if (res.data.success === true) {
      ElMessage.success('激活成功,请重新登录')
      register=reactive({})
      phoneBindDialog=false
      router.go(0)
    } else {
    }
  })
  init()
}
const close=()=>{
  isShow.value=false
}
const fail=()=>{
  ElMessage.error('验证失败')
}

let register = reactive({

  username: '',
  code: '',
  phone: '',
  random: '',
  password: ''

})
const init=()=>{
  register = reactive({
    username: '',
    code: '',
    phone: '',
    random: '',
    password: ''

  })
}
const cancel=()=>{
  firstLogin.value=false
  init()
}

let userInfoFormRules = reactive({
  username: [
    {required: true, message: "请输入用户名", trigger: "blur"}
  ],
  realname: [{required: true, message: "请输入姓名", trigger: "blur"}],
  password: [{required: true, message: "请输入密码", trigger: "blur"}],
  mobile: [
    {
      required: true,
      validator: function (rule, value, callback) {
        const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
        if (register.phone == null) {
          callback(new Error("请输入手机号码"));
        } else if (regMobile.test(register.phone) == false) {
          callback(new Error("输入的手机号码格式错误"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  email: [
    {
      required: true,
      message: "请输入邮箱",
      trigger: "blur"
    },
    {
      validator: function (rule, value, callback) {
        if (
            /^\w{1,64}@[a-z0-9\-]{1,256}(\.[a-z]{2,6}){1,2}$/i.test(
                value
            ) == false
        ) {
          callback(new Error("邮箱格式错误"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
})

const loginForm = reactive({
  username: '',
  password: '',
  code: '',
  phone: '',
  random: '',
  role: '3',
  identify: 3
})

let firstLogin = ref(false)


// const store = useStore()

let phoneBindDialog = ref(true);





const loginFormRules = reactive({
  username: [
    {required: true, message: '账户不可为空', trigger: 'blur'},
    {max: 20, message: '长度在 20 个字符以内', trigger: 'change'}
  ],
  password: [+
    {required: true, message: '密码不可为空', trigger: 'blur'},
    {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'change'}
  ]
})
const router = useRouter()


let param = reactive({})
let registerSubmitForm = reactive({
  username: '',
  password:'',
  phone: '',
  realName: '',
  sex: 1,
  code: '',
  random: '',
  type: 2
})
const getCode = () => {
  if(!register.username){
    ElMessage.error('请输入用户名')
  }
  else if(!register.phone){
    ElMessage.error('请输入手机号')
  }
  else if(!register.password){
    ElMessage.error('请输入新密码')
  }
  else{
    isShow.value=true
  }
}





const loginSubmit = () => {
  param.type = 2
  param.loginStatus = '2'
    API.getPublic().then((res) => {
      console.log(res)
      if (res.data.code === '0') {
        // 使用jsencrypt加密
        const entry = new JSEncrypt()
        entry.setPublicKey(res.data.content.publicKeyStr)
        param.phone =  entry.encrypt(loginForm.phone)
        param.password =entry.encrypt(loginForm.password)
        param.random = res.data.content.random
        API.userLogin(param).then((result) => {
          if (result.data.code === '0') {
            let token=result.data.content.token
            localStorage.setItem('token', token)
            API.userInfo({
              phone:loginForm.phone,
              size:1,
              current:1
            }).then(res1=>{
              if(res1.data.content.records[0].identify===3){
                if (result.data.content.status === "1") {
                  firstLogin.value = true
                } else {
                  if (firstLogin.value === true) {
                    phoneBindDialog.value = true
                  } else {
                    localStorage.setItem('loginuserphone',loginForm.phone)
                    localStorage.setItem('userName',loginForm.username)
                    store.commit('user/logined')
                    router.push({path: '/public'})
                  }
                }
              }
              else{
                ElMessage.error('身份错误！当前为培训师端')
              }
            })

          }
        }).catch(res=>{
          ElMessage.error(res.response.data.message)
        })
      }

    }).catch(error => {
      console.log(error)
    })

}
</script>

<style scoped>

.login {
  position: fixed;
  height: 100%;
  width: 100%;
  background: url("../assets/bg-login.png") no-repeat center;
  background-size: 100% 100%;
  color: white;
}

.login-form-container {
  position: absolute;
  left: 60%;
  top: 28%;
  width: 520px;
  height: 400px;
  background-color: #D1FCF4;
  border-radius: 2%;
}

.login-form {
  position: absolute;
  left: 0;
  right: 0;
  width: 450px;
  padding: 0px 35px 10px 35px;
  margin: 15px auto;
}

.title-container .title {
  font-size: 50px;
  color: #eee;
  margin: 7% auto 40px auto;
  text-align: center;
  font-family: Serif;
}

.registerPhone {
  margin-bottom: 30px;
}

.login .el-form-item {
  border: 1px solid rgba(255, 255, 255, 0.1);
  /* background: rgba(133, 129, 129, 0.1); */
  border-radius: 5px;
  /* color: #454545; */
  width: 320px;
  height: 60px;
  margin: 0px auto 10px auto;
}

.el-form-item .prep-icon-span {
  font-size: 20px;
}

.el-button {
  display: block;
  width: 320px;
  margin: 25px auto;
  background-image: linear-gradient(#81E6D4, #16AF93);
  border-radius: 10px;
  font-size: 20px;
  font-weight: bold;
}
.el-button.login-button{
  background:white;
  width: 120px;
  border: 1px solid;
  background-color: transparent;
  text-transform: uppercase;
  font-size: 15px;
  padding: 10px 20px;
  font-weight: 400;
}
.el-button.login-button1{
  background:white;
  width: 220px;
  border: 0.5px solid;
  text-transform: uppercase;
  font-size: 15px;
  padding: 10px 40px;
  font-weight: 400;
}
a {
  font-size: 13px;
  color: black;
  cursor: pointer;
  text-decoration: none;
  margin-left: 20px;
}

.codeDiv {
  width: 100%;
  display: flex;
}

.registerCode {
  margin-top: 28px;
  margin-right: 10px;
  height: 50%;
  flex-grow: 3; /* 占据四分之三宽度 */

}

.getRegisterCode {

  flex-grow: 1; /* 占据四分之一宽度 */
}


</style>
